// 文件上传处理 multer
var multer  = require('multer');
var mkdir = require('../dao/mkdir')
var utils = require('../dao/utils')

var {apiSuccess,apiError} = require('../dao/apirequest')


// 控制文件的存储
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // console.log('destination 1',req.files)
        // console.log('destination 2  '+req.body)
        // console.log('destination 3',file)
        // let {url} = req.body
        let test = '2020-11-25'
         test = new Date().Format("yyyy-MM-dd")
        //  console.log(test)

        mkdir.mkdirs('../data/'+test,err=>{
            console.log(err)
        })

      cb(null, './data/'+test)
    },
    filename: function (req, file, cb) {
        // console.log('filename1',req.files)
        // console.log('filename2',req.body)
        // console.log('filename3',file)

        // file 数据格式如下
        // file ={
        //     "fieldname": "file",
        //     "originalname": "testimg.jpg",
        //     "encoding": "7bit",
        //     "mimetype": "image/jpeg"
        // }

        // 正则匹配后缀名
        let type = file.originalname.replace(/.+\./,'.')
      cb(null, Date.now()+type)
    }
  })
  

  var upload = multer({ storage: storage })

  module.exports = function(app){

    // ----------* 文件相关接口  files *---------- 
    /**
     * 
     * @api {post} /files/upload 文件上传
     * @apiName 文件上传
     * @apiGroup files
     * @apiVersion  0.0.1
     * 
     */
      app.post('/files/upload',upload.array('file',10),function (req,res,next){
        
        console.log('upload1',req.files)
        console.log('upload2',req.body)
          let data = req.files;
          res.send(data);
      })

    /**
     * 
     * @api {post} /files/test 测试
     * @apiName  测试
     * @apiGroup files
     * @apiVersion  0.0.1
     * 
     */
      app.post('/files/test',(req,res)=>{
      //  let test = new Date().Format("yyyy-MM-dd")
      //    console.log(test)
          res.send(apiSuccess())
      })
      app.get('/files/test',(req,res)=>{
          let test = new Date().Format("yyyy-MM-dd hh:mm:ss")
          console.log((new Date()).Format("yyyy-MM-dd hh:mm:ss")); // 2018-08-02 21:22:07
          res.send(apiSuccess(test))
      })
  }